<?php
	class CategoryControl extends Control{

		function __auto(){
			C("debug",0);
		}
		//栏目管理视图
		function index(){
			$db = M("category");
			//无限极分类方法一 使用path 0_1_3方式
			/*$order = "concat(path,'_',cid)";
			$data = $db->order($order)->all();
			if($data){
		    	foreach($data as $k=>$c){

		    		$count = count(explode("_", $c['path']))-1;
		    		$data[$k]['html'] = str_repeat("&nbsp;", $count*2);
		    	}
    		}*/
    		//无限极分类方法二 使用pid 方式递归遍历
    		$data = $db->all();
    		$catData = $this->channel($data);
			$this->assign("data",$catData);
			$this->display();
		}

		//递归无限极分类
		function channel($data,$fieldId='cid',$fieldPid='pid',$pid=0,$html='----',$level=0){
			static $arr = array();
			static $id = 0;
			foreach($data as $d){
				if($d[$fieldPid]==$pid){
					$arr[$id] = $d;
					$arr[$id]['level'] =$level;
					$arr[$id]['html'] = str_repeat($html, $level);
					$id++;
					$this->channel($data,$fieldId,$fieldPid,$d[$fieldId],$html,$level+1);
				}
			}
			return $arr;
		}

		//添加栏目视图
		function addShow(){

			//中文正则
			// $preg = "/^[\x{4e00}-\x{9fa5}]+$/u";
			// p(preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", "zhao照"));
			// if(preg_match($preg, "照")){
			// 	echo 1;
			// }else{
			// 	echo 2;
			// }
			$this->display();
		}

		//添加栏目到数据库
		function add(){
			$db = M("category");
	    	if($db->add()){
	    		$this->success("添加栏目成功","index");
	    	}else{
	    		$this->error("栏目添加失败");
	    	}
		}

		//编辑栏目
		function editShow(){

			$cid = $this->_get();
			if($cid){
				$db = M("category");
				$field = $db->find($cid);
				$this->assign("field",$field);
			}
			$this->display();
		}

		//修改栏目数据
		function save(){
			C("debug",1);
			$cid = $this->_post();
			if($cid){
				$db = M("category");
				
				if($db->save()){
					$this->success("修改栏目数据成功！","index");
				}else{
					$this->error("修改栏目数据失败，请更改栏目数据后在提交！","index");
				}
			}
		}
		//删除栏目数据
		function delcategory(){
			$cid =$this->_get('cid');
			if($cid){
				$db = M("category");
				$data = array();//返回客户端的数据
				if($db->find("pid=".$cid)){
					$data['state'] = "error";
					$data['msg'] = "请先删除子栏目！";
				}else if($db->table("arc")->find("cid=".$cid)){
					$data['state'] = "error";
					$data['msg'] = "请先删除栏目下的文章！";
				}else{
					if($db->del($cid)){
						$data['state'] = "";
					}else{
						$data['state'] = "error";
						$data['msg'] = "删除失败，请重试！";
					}	
				}
				echo json_encode($data);
			}
		}

		//异步验证栏目名称是否存在
		function ajaxCateName(){
			if(isset($_GET['catename'])){
				$catename = $_GET['catename'];
				$db = M("category");
				$result = $db->where(array('catname'=>$catename))->find();
				if($result){
					echo 1;
				}
			}
		}


	}
?>